package com.icehand.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;

/**
 * 文件上传S
 * Created by icehand on 2017/5/15.
 */
@Controller
@RequestMapping(value ="/file")
public class FileUploadController {

	@RequestMapping("")
	public String file(){
		return "/file";
	}

	@RequestMapping("/batch")
	public String batch(){
		return "/mutifile";
	}

	@RequestMapping("/upload")
	public @ResponseBody String  handleFileUpload(@RequestParam("file")MultipartFile file){
		if(file.isEmpty()){
			return "文件为空，请重传";
		}

		try {
			BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename())));
			out.write(file.getBytes());
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return "文件不存在，请重传";
		} catch (IOException e) {
			e.printStackTrace();
			return "上传失败，服务器异常";
		}
		return "上传成功";
	}

	@RequestMapping(value = "/batch/upload",method = RequestMethod.POST)
	public @ResponseBody String handleBatchFileUpload(HttpServletRequest request){
		List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("file");
		MultipartFile file;
		BufferedOutputStream stream;
		for (int i =0; i< files.size(); ++i) {
			file = files.get(i);
			if (!file.isEmpty()) {
				try {
					byte[] bytes = file.getBytes();
					stream =
							new BufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename())));
					stream.write(bytes);
					stream.close();
				} catch (Exception e) {
					stream =  null;
					return "You failed to upload " + i + " => " + e.getMessage();
				}
			} else {
				return "You failed to upload " + i + " because the file was empty.";
			}
		}
		return "上传成功";
	}
}
